package com.foreverwin.mes.lims.service.impl;

import com.foreverwin.mes.common.enums.IDUtils;
import com.foreverwin.mes.core.base.FrontPage;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.dto.InactiveTimeDto;
import com.foreverwin.mes.lims.mapper.InactiveTimeItemMapper;
import com.foreverwin.mes.lims.model.InactiveTime;
import com.foreverwin.mes.lims.mapper.InactiveTimeMapper;
import com.foreverwin.mes.lims.model.InactiveTimeItem;
import com.foreverwin.mes.lims.service.InactiveTimeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.foreverwin.mes.meapi.model.CustomFields;
import com.foreverwin.mes.meapi.model.Resrce;
import com.foreverwin.mes.meapi.model.UserGroup;
import com.foreverwin.mes.meapi.service.CustomFieldsService;
import com.foreverwin.mes.meapi.service.ResrceService;
import com.foreverwin.mes.meapi.service.UserGroupService;
import com.foreverwin.mes.production.model.CleanDataItem;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
/**
 * <p>
 * 呆滞时间设置 服务实现类
 * </p>
 *
 * @author Max
 * @since 2020-03-09
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class InactiveTimeServiceImpl extends ServiceImpl<InactiveTimeMapper, InactiveTime> implements InactiveTimeService {


    @Autowired
    private InactiveTimeMapper inactiveTimeMapper;
    @Autowired
    private InactiveTimeItemMapper inactiveTimeItemMapper;
    @Autowired
    private CustomFieldsService customFieldsService;
    @Autowired
    private ResrceService resrceService;
    @Autowired
    private UserGroupService userGroupService;

    @Override
    public Page<InactiveTime> selectPage(FrontPage<InactiveTime> frontPage, InactiveTime inactiveTime) {
        EntityWrapper<InactiveTime> queryWrapper = new EntityWrapper<>();
        queryWrapper.setEntity(inactiveTime);
        return super.selectPage(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<InactiveTime> selectList(InactiveTime inactiveTime) {
        EntityWrapper<InactiveTime> queryWrapper = new EntityWrapper<>();
        queryWrapper.setEntity(inactiveTime);
        return super.selectList(queryWrapper);
    }

    /**
     * 查询呆滞时间设置
     *
     * @param inactiveTime
     * @return
     */
    @Override
    public List<InactiveTimeItem> selectTimeSetList(InactiveTime inactiveTime) {
        String resrce = inactiveTime.getResrce();
        String item = inactiveTime.getItem();
        InactiveTime inactive = new InactiveTime();
        inactive.setResrce( resrce );
        inactive.setItem( item );
        InactiveTime inactiveTime1 = inactiveTimeMapper.selectOne( inactive );
        if (inactiveTime1 == null) {
            throw BusinessException.build("资源："+ resrce + "与物料"+ item + "未设置时间管控");
        }

        String zInactiveTimeBo = inactiveTime1.getHandle();
        InactiveTimeItem inactiveTimeItem = new InactiveTimeItem();
        inactiveTimeItem.setzInactiveTimeBo(zInactiveTimeBo);
        EntityWrapper<InactiveTimeItem> entityWrapper = new EntityWrapper<>();
        entityWrapper.setEntity(inactiveTimeItem);
        List<InactiveTimeItem> list = inactiveTimeItemMapper.selectList(entityWrapper);
        if ( list == null || list.size()==0 ) {
            throw BusinessException.build("资源："+ resrce + "与物料"+ item + "未维呆滞时间默认下限为0");
        }
        return list;
    }

    /**
     * 保存或更新呆滞时间设置
     *
     * @param inactiveTimeDto
     * @return
     */
    @Override
    public int insertOrUpdateTimeSetList(InactiveTimeDto inactiveTimeDto) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        //检查时间设置明细是否符合规则
        List<InactiveTimeItem> inactiveTimeItemList = inactiveTimeDto.getInactiveTimeItemList();
        if ( inactiveTimeItemList != null && inactiveTimeItemList.size() > 2 ) {
            throw BusinessException.build("设置数量不能超过2笔，请重新设置");
        }

        int lowerLimit = 0;
        int upperLimit = 0;
        if ( inactiveTimeItemList != null && inactiveTimeItemList.size() > 0 ) {
            for (InactiveTimeItem itil : inactiveTimeItemList) {
                if (">".equals(itil.getPattern())) {
                    lowerLimit = itil.getControlTime();
                } else if ("<".equals(itil.getPattern())) {
                    upperLimit = itil.getControlTime();
                }
            }
            if (lowerLimit >= upperLimit) {
                throw BusinessException.build("下限的值不能大于上限值");
            }
        }
        String resrce = inactiveTimeDto.getResrce();
        String item = inactiveTimeDto.getItem();


        InactiveTime inactive = new InactiveTime();
        inactive.setResrce( resrce );
        inactive.setItem( item );
        InactiveTime inactiveTime1 = inactiveTimeMapper.selectOne( inactive );
        if (inactiveTime1 == null) {
            inactive.setHandle( IDUtils.createID() );
            inactive.setSite( site );
            inactive.setResrceDesc( inactiveTimeDto.getResrceDesc() );
            inactive.setItemDesc( inactiveTimeDto.getItemDesc() );
            //设置罐子用途
            Resrce _resrce = resrceService.selectByCode( site,resrce);
            String resrceBo =_resrce.getHandle();
            CustomFields tankByUseField = customFieldsService.getAttributeValue( resrceBo,"TANK_BY_USE");
            if ( tankByUseField != null ) {
                String tankByUse = tankByUseField.getValue();
                inactive.setTankByUse( tankByUse );
            }
            CustomFields shortCodeField = customFieldsService.getAttributeValue( resrceBo,"SHORT_CODE");
            if ( shortCodeField != null ) {
                String shortCode = shortCodeField.getValue();
                inactive.setShortCode( shortCode );
            }
            //设置上下限
            inactive.setLowerLimit( lowerLimit );
            inactive.setUpperLimit( upperLimit );
            //设置提醒方式和提醒用户组
            /*inactive.setRemindType();
            inactive.setRemindUserGroup();*/
            inactive.setCreator( user );
            inactive.setUpdater( user );
            inactive.setCreatedDateTime( new Date() );
            inactive.setModifiedDateTime( new Date() );
            inactiveTimeMapper.insert(inactive);
        } else {
            InactiveTimeItem inactiveTimeItem = new InactiveTimeItem();
            EntityWrapper<InactiveTimeItem> ew = new EntityWrapper();
            inactiveTimeItem.setzInactiveTimeBo( inactiveTime1.getHandle() );
            ew.setEntity( inactiveTimeItem );
            inactiveTimeItemMapper.delete( ew );
            inactiveTime1.setLowerLimit( lowerLimit );
            inactiveTime1.setUpperLimit( upperLimit );
            inactiveTime1.setUpdater( user );
            inactiveTime1.setModifiedDateTime( new Date() );
            inactiveTimeMapper.updateById( inactiveTime1 );
        }

        String inactiveTimeBo = "";
        if ( inactive.getHandle()== null || "".equals( inactive.getHandle() ) ) {
            inactiveTimeBo = inactiveTime1.getHandle();
        } else {
            inactiveTimeBo = inactive.getHandle();
        }
        int j=0;
        for ( int i=0;i<inactiveTimeItemList.size();i++ ) {
            InactiveTimeItem inactiveTimeItem = inactiveTimeItemList.get(i);
            inactiveTimeItem.setHandle( IDUtils.createID() );
            inactiveTimeItem.setzInactiveTimeBo( inactiveTimeBo );

            String userGroup = inactiveTimeItem.getRemindUserGroup();
            //if (userGroup != null || !"".equals( userGroup )) {
            if (userGroup != null && !StringUtils.isBlank(userGroup)) {
                UserGroup ug = new UserGroup();
                EntityWrapper<UserGroup> ew = new EntityWrapper();
                ug.setUserGroup(userGroup);
                ew.setEntity(ug);
                UserGroup _ug = userGroupService.selectOne(ew);
                if (_ug == null) {
                    throw BusinessException.build("用户组不存在，请检查");
                }
            }
            inactiveTimeItem.setCreator( user );
            inactiveTimeItem.setUpdater( user );
            inactiveTimeItem.setCreatedDateTime( new Date() );
            inactiveTimeItem.setModifiedDateTime( new Date() );
             j += inactiveTimeItemMapper.insert( inactiveTimeItem );
        }
        return j;
    }


}